var columnReadyCounter = 0;

// This is the callback function for the "hiding" animations
// it gets called for each animation (since we don't know which is slowest)
// the third time it's called, then it resets the column positions
function ifReadyThenReset() {

	columnReadyCounter++;
	
	if (columnReadyCounter == 1) {
		$(".col").not(".current .col").css("top", 1000);
		columnReadyCounter = 0;
	}

};

$(document).ready(function() {
	var lastUpdatedAt = new Date();
	    lastUpdatedAt.setMonth(lastUpdatedAt.getMonth() - 1);
	$('#select-services').each(function() {
		var handleSuccess = function(result) {
    		var $form = $("#select-services");
    		if (result.length > 0) {
        		$form.hide();
                var $select = $form.find("select"),
                    $buttons = $("#service-buttons");

                $.each(result, function() {
                        var opt = $("<option></option>").attr("value", this["key"]).html(this["name"]);
                        var link = $("<a></a>").html(this["name"]).attr("href", "#").data("key", this["key"]).click(function(){
                        	$select.val($(this).data("key"));
                        	$form.submit();
                        	return false;
                        });
                        $buttons.prepend(link);
                        $select.append(opt);
                });
    		} else {
    			$form.closest('.service').hide();
    		}
    	}
        $.ajax({url: "/services", dataType: "json",
                success: handleSuccess}
        );
    });

    /**
     * Toggle switch for client token (a.k.a. userID string)
     */
    $("a[href=#more]").click(function() {
    	$('#more').toggle();
        if ($('#more').is(':visible'))
            $(this).text('Close');
        else
            $(this).text('Open');
    	return false;
    });

    /**
     * Renderer for each news item which is retrieved from server side.
     */
    $.template('news_item', '<div class="news">'
            + '<div class="title"><h3><a href="#">${Title}</a></h3>'
            + '<a href="${Url}" target="_blank">&raquo;</a></div>'
            + '<p class="invisible">${Content}</p></div>');
    $('.title > h3').live('click', function() {
        $(this).parent().next('p').toggle();
    });

    $('#news').each(function() {
        var renderService = function(service) {
            var $service = $("#service_" + service["key"]),
                data = [];
            if ($service.size() == 0) {
                $service = $("<div class='service' id='service_" + service["key"] + "'></div>");
                $("<div class='title'></div>").html(service["name"]).appendTo($service);
            }
            $.each(service["news"], function() {
                var dt = {}
                dt['Title'] = this['title'] || '---';
                dt['Url'] = this['targetUrl'];
                dt['CreatedAt'] = this['createdAt'];
                dt['Author'] = this['author'];
                dt['Content'] = this['content'] || '';
                data.push(dt);
            });
            $.tmpl('news_item', data).appendTo($service);
            return $service;
        };

    	var newsSuccessHandler = function(result){
			var $news = $("#news");
			$.each(result, function(){
				$news.prepend(renderService(this));
			});
			lastUpdatedAt = new Date();
		};

		var updateNews = function(){
			// console.log("Update news since " + lastUpdatedAt.toISOString());
			$.ajax({
				url: "/news",
				dataType: "json",
				data: {since: lastUpdatedAt.toISOString()},
				success: newsSuccessHandler
			});
			setTimeout(updateNews, 60 * 1000);
		};
		updateNews();
    });

    /**
     * Tab manager on top page.
     */
	var $allContentBoxes = $(".content"),
	    $allTabs = $(".tabs li a"),
	    $el, $colOne,
	    hrefSelector = "",
	    speedOne = 1000;

	// first tab and first content box are default current
	$(".tabs li:first-child a, .content:first").addClass("current");
	$(".content-wrapper .current .col").css("top", 0);
	
	$("#main-content").delegate(".tabs a", "click", function() {
		
		$el = $(this);

		if ( (!$el.hasClass("current")) && ($(":animated").length == 0 ) ) {
		
			// current tab correctly set
			$allTabs.removeClass("current");
			$el.addClass("current");
			
			// each column is animated upwards to hide
			// kind of annoyingly redudundant code
			$colOne = $(".content-wrapper .current .col-one");
			$colOne.animate({
				"top": -$colOne.height()
			}, speedOne);
		
			// new content box is marked as current
			$allContentBoxes.removeClass("current");		
			hrefSelector = $el.attr("href");
			$(hrefSelector).addClass("current");
		
			// columns from new content area are moved up from the bottom
			// also annoying redundant and triple callback seems weird
			$(".content-wrapper .current .col-one").animate({
				"top": 0
			}, speedOne, function() {
				ifReadyThenReset();
			});
		};

	});
});

